﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace demo_web_uploadface.v2
{
    public partial class upload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var flag = Request["flag"] ?? "";
            if (string.IsNullOrEmpty(flag)) return;

            if (flag == "upload") UploadFile();
            if (flag == "crop") CropFile();
        }

        private void CropFile()
        {
            //图片的路径
            var fileName = Request["filename"] ?? "";
            var bili = Request["bili"] ?? "";
            var top = Request["top"] ?? "";
            var left = Request["left"] ?? "";
            var width = Request["width"] ?? "";
            var height = Request["height"] ?? "";

            //上面任何一个数据不传递，抛出异常
            //自己写检测代码

            Bitmap map = new Bitmap(Server.MapPath(fileName));
            Bitmap newMap = new Bitmap(map,
                (int)(map.Width * float.Parse(bili)),
                (int)(map.Height * float.Parse(bili)));
            if (map != null) map.Dispose();

            //选择图片的一部分
            Bitmap retMap = new Bitmap(int.Parse(width), int.Parse(height));
            Graphics g = Graphics.FromImage(retMap);
            g.DrawImage(newMap, float.Parse(left), float.Parse(top));
            g.Dispose();
            if (newMap != null) newMap.Dispose();

            //新的文件名称
            var newFilename = "upload/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
            retMap.Save(
                Server.MapPath(newFilename),
                ImageFormat.Jpeg
                );

            //Response.ContentType = "application/json";
            Response.Write("{'width':" + retMap.Width + ",'height':" + retMap.Height + ",'link':\'" + newFilename + "\'}");

            if (retMap != null) retMap.Dispose();
            Response.End();
        }

        /// <summary>
        /// 简单的上传，真实的情况下要验证后缀 大小 等
        /// </summary>
        private void UploadFile()
        {
            var files = Request.Files;
            if (files.Count == 0) return;

            var file = files[0];
            Bitmap map = new Bitmap(file.InputStream);

            //这里的文件名称根据自己的业务生成，我这里简化了。
            var fileName = "upload/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
            map.Save(
                Server.MapPath(fileName),
                ImageFormat.Jpeg
                );

            //Response.ContentType = "application/json";
            Response.Write("{'width':"+ map.Width + ",'height':"+ map.Height + ",'link':\'"+ fileName + "\'}");

            if(map!=null) map.Dispose();
            Response.End();
        }
    }
}